//
//  AppDelegate.m
//  ShoppingMall
//
//  Created by 华谕 on 2017/11/10.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "AppDelegate.h"
#import "YDYViewController.h"

@interface AppDelegate ()<WXApiDelegate>
@property (nonatomic, strong)NSString *code;
@property (nonatomic, strong)NSString *updateurl;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//    [self requestCheckVersion];
//    [self getapp_Version];
    [WXApi registerApp:@"wxf0b89b6b8336a7fa"];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self loadRootViewController];
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)loadRootViewController
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    [LTools cache:app_Version ForKey:kAppVersion];
    BOOL K = [LTools storageForKey:app_Version];
    if (K)
    {
        
        self.tabbarViewController = [[HYTabBarViewController alloc] init];
        self.window.rootViewController = _tabbarViewController;
    }
    else
    {
        //用户未安装过，则展示引导页
        YDYViewController *ydyVc = [[YDYViewController alloc] init];
        self.window.rootViewController = ydyVc;
    }

}

- (void)requestCheckVersion
{
    NSDictionary *dic = @{@"version":@"4"};
//    [HYBaseHandler requestCheckVersionParmers:dic Success:^(id obj) {
//        if ([obj server_Getcodecheck])
//        {
//            NSString *str = obj[@"data"];
//            if ([str integerValue] == 0)
//            {
//                [LTools storage:NO ForKey:SERVER_isPass];
//                
//            }
//            else
//            {
//                [LTools storage:YES ForKey:SERVER_isPass];
//            }
//        }
//        
//    } failed:^(NSError *error) {
//        
//    }];
}

- (void)getapp_Version
{
    //获取版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //版本号信息存到NSUserDefaults沙盒
    [LTools cache:app_Version ForKey:kAppVersion];
    //如果有更新的版本，提醒用户下载
    [self getUpdateInformation];
    
}

- (void)getUpdateInformation
{
    [LTools versionForAppid:@"1330934153" Block:^(BOOL isNewVersion, NSString *updateUrl, NSString *updateContent)
     {
         if (isNewVersion==YES)
         {
             self.updateurl = updateUrl;
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"印港在线提醒您有新版本" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
             alert.tag = 1015;
             [alert show];
         }
     }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1015)
    {
        if(buttonIndex==1)
        {
            NSURL *url = [NSURL URLWithString:self.updateurl];
            [[UIApplication sharedApplication]openURL:url];
        }
        
    }
}

// 这个方法是用于从微信返回第三方App
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    
    [WXApi handleOpenURL:url delegate:self];
    
    return YES;
}


// 微信 授权后回调
- (void)onResp:(BaseResp *)resp{
    
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        
    }
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        //        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        //
        //        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        //        [alertview show];
        
    }
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode)
        {
            case WXSuccess:
            {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //                发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
                break;
            }
                
            default:
            {
                //                [LTools showMBProgressWithText:@"付款失败" addToView:self.window];
                break;
            }
        }
    }
    
    
    
    
}



- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            int resultStatus=[[resultDic objectForKey:@"resultStatus"]intValue];
            if (resultStatus==9000) {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
            }else{
            }
            
        }];
        return YES;
    }
    
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            int resultStatus = [[resultDic objectForKey:@"resultStatus"] intValue];
            
            //支付宝支付成功
            if (resultStatus==9000) {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
            }
            //支付宝支付失败
            else{
                
            }
            
        }];
        return YES;
    }
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    return YES;
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
